<?php

namespace app\admin\controller;

use app\admin\model\Config as ConfigModel;
use app\admin\model\ConfigCate as ConfigCateModel;
use think\facade\View;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;

class System extends Base
{
    private function get_dir($path)
    {
        $no_dir = [
            // root_path() . 'addons',
            root_path() . 'config/addons.php',
            root_path() . 'config/app.php',
            root_path() . 'config/cache.php',
            root_path() . 'config/console.php',
            root_path() . 'config/cookie.php',
            root_path() . 'config/database.php',
            root_path() . 'config/filesystem.php',
            root_path() . 'config/lang.php',
            root_path() . 'config/log.php',
            root_path() . 'config/middleware.php',
            root_path() . 'config/session.php',
            root_path() . 'config/route.php',
            root_path() . 'config/trace.php',
            root_path() . 'runtime', 
            root_path() . 'upload',
            root_path() . '.env',
            root_path() . '.user.ini',
        ];
        $list = [];
        foreach (scandir($path) as $v) {
            if ($v == ".." || $v == "."||in_array($path. "/" . $v,$no_dir)) continue;
            if (is_dir($path . '/' . $v)) {
                $list = array_merge($list, $this->get_dir($path . "/" . $v));
            }else{
                $list[] = [
                    'path'      =>  str_replace(root_path(),'',$path . "/" . $v),
                    'md5'       =>  md5_file($path . '/' . $v)
                ];
            }
        }
        return $list;
    }
    public function upgrade()
    {
        if($this->request->isAjax()){
            if($this->request->isGet()){
                //获取本地文件
                $list = $this->get_dir(substr(root_path(),0,-1));
                $version = Config::get('jsuphp.version');
                $result = curl('http://upgrade.jsuphp.com',[
                    'method'    =>  'upgrade://api/upgrade',
                    'version'   =>  $version,
                    'files'     =>  $list,
                    'password'  =>  $this->get['password'],
                    'domain'    =>  $this->request->server('HTTP_HOST'),
                ],'json');
                $result = json_decode($result,true);
                if($result['code']==0){
                    return $this->error($result['msg'],$result['url']??'');
                }
                return $this->success('检查成功','',$result['data']);
            }elseif($this->request->isPost()){
                //获取本地文件
                $list = $this->get_dir(substr(root_path(),0,-1));
                $version = Config::get('jsuphp.version');
                $result = curl('http://upgrade.jsuphp.com',[
                    'method'    =>  'upgrade://api/upgrade',
                    'version'   =>  $version,
                    'files'     =>  $list,
                    'password'  =>  $this->post['password'],
                    'domain'    =>  $this->request->server('HTTP_HOST'),
                ],'json');
                $result = json_decode($result,true);
                if($result['code']==0){
                    return $this->error($result['msg'],$result['url']??'');
                }
                $files = $result['data']['files'];
                
                foreach($files as $v){
                    $path = root_path().pathinfo($v['path'],PATHINFO_DIRNAME);
                    if(!is_dir($path)){
                        mkdir($path,0755,true);
                    }
                    file_put_contents(root_path().$v['path'],base64_decode($v['content']));
                }
                
                $sqls = $result['data']['sqls'];
                foreach($sqls as $v){
                    $this->importsql(base64_decode($v));
                }
                
                return $this->success('更新成功');
            } 
        }
        //线上版本
        $server_version = curl('http://upgrade.jsuphp.com?method=upgrade://api/get_version');
        $upgrade_log = curl('http://upgrade.jsuphp.com?method=upgrade://api/upgrade_log');
        return $this->fetch('',['server_version'=>$server_version,'upgrade_log'=>json_decode($upgrade_log,true)]);
    }
    
    public function importsql($sql)
    {
        $prefix = Config::get('database.connections.mysql.prefix');
        $sql = str_replace("\r", "\n", str_replace('jsu_', $prefix, $sql));
        $ret = array();
        $num = 0;
        foreach (explode(";\n", trim($sql)) as $query) {
            $ret[$num] = '';
            $queries = explode("\n", trim($query));
            foreach ($queries as $query) {
                $ret[$num] .= (isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $query[0].$query[1] == '--') ? '' : $query;
            }
            $num++;
        }
        unset($sql);
        foreach ($ret as $query) {
            $query = trim($query);
            if ($query) {
                if (substr($query, 0, 12) == 'CREATE TABLE') {
                    $line = explode('`', $query);
                    $data_name = $line[1];
                    Db::execute($query);
                    unset($line, $data_name);
                } else {
                    Db::execute($query);
                }
            }
        }
    }
}
